/**
 * jsonp: 前端传一个自定义方法 调后端接口时调用前端自定义的方法
 *
 * */

const http = require("http")
const https = require("https")
const url = require("url");
const cheerio = require("cheerio")
const bodyParser = require("body-parser")

http.createServer((req, res) => {
  const urlObj = url.parse(req.url, true)
  res.writeHead(200, {
    "Content-Type": "application/json;charseclear" +
      "t=utf-8",
    // cors 头
    "access-control-allow-origin": "*"
  })
  switch (urlObj.pathname) {
    case "/api/aaa":
     // 客户端去 猫眼要数据
      console.log(bodyParser.json())
      /* httpget((data) => {
        res.end(spider(data))
      })*/
     // console.log(req)
      res.end("hello world")
      break;
    default:
      res.end("404")
  }
}).listen(3000)


function httpget(cb) {
  let data = ''
  https.get(`https://i.maoyan.com`,
    (res) =>  {
      res.on("data", (chunk)=> {
        data+= chunk
      })
      res.on("end", ()=> {
        cb(data)
      })
    })
}


function spider(data) {
  // npm i cheerio 可以像 jquery 那样用

  let $ = cheerio.load(data)
  let $moviewlist = $(".column.content")
  let movies = []
  $moviewlist.each((index, value) => {
    movies.push({
      title: $(value).find(".title").text(),
      grade: $(value).find(".grade").text(),
      actor: $(value).find(".actor").text(),
    })
  })
  return JSON.stringify(movies)
}